package models

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"reflect"
	"strings"
	"time"

	"github.com/astaxie/beego/orm"
	"gitee.com/lzqysoft/ims/libs"
)

type ImsSequenceParams struct {
	Id         string       `orm:"column(id);pk"`
	Type       int       `orm:"column(type);null"`
	Seq        int       `orm:"column(seq);null"`
	Remark     string    `orm:"column(remark);null"`
	Status     int       `orm:"column(status);null"`
	Isdelete   int       `orm:"column(isdelete);null"`
	Ctime      time.Time `orm:"column(ctime);type(timestamp with time zone);null"`
	Creater    string    `orm:"column(creater);null"`
	CId        string    `orm:"column(c_id);null"`
	Utime      time.Time `orm:"column(utime);type(timestamp with time zone);null"`
	Updater    string    `orm:"column(updater);null"`
	UId        string    `orm:"column(u_id);null"`
	OrgId      string    `orm:"column(org_id);null"`
	DeptId     string    `orm:"column(dept_id);null"`
	SequenceId string    `orm:"column(sequence_id);null"`
	Start      time.Time `orm:"column(start);type(timestamp with time zone);null"`
	End        time.Time `orm:"column(end);type(timestamp with time zone);null"`
	Count      int       `orm:"column(count);null"`
	Outlay     float64   `orm:"column(outlay);null"`
}

func (t *ImsSequenceParams) TableName() string {
	return "ims_sequence_params"
}

func init() {
	orm.RegisterModel(new(ImsSequenceParams))
}

// AddImsSequenceParams insert a new ImsSequenceParams into database and returns
// last inserted Id on success.
func AddImsSequenceParams(m *ImsSequenceParams) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetImsSequenceParamsById retrieves ImsSequenceParams by Id. Returns error if
// Id doesn't exist
func GetImsSequenceParamsById(id string) (v *ImsSequenceParams, err error) {
	o := orm.NewOrm()
	v = &ImsSequenceParams{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllImsSequenceParams retrieves all ImsSequenceParams matches certain condition. Returns empty list if
// no records exist
func GetAllImsSequenceParams(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(ImsSequenceParams))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []ImsSequenceParams
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateImsSequenceParams updates ImsSequenceParams by Id and returns error if
// the record to be updated doesn't exist
func UpdateImsSequenceParamsById(m *ImsSequenceParams) (err error) {
	o := orm.NewOrm()
	v := ImsSequenceParams{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func UpdateImsSequenceParams (m []ImsSequenceParams, user *User) (err error) {
	o := orm.NewOrm()
	o.Begin()
	for k, _ := range  m {
		m[k].Updater = user.Abbr
		m[k].Utime = time.Now()
		m[k].UId = user.Id
		_, err = o.Update(&m[k])
		if err != nil {
			beego.Debug(err)
			o.Rollback()
			return err
		}
	}
	return o.Commit()
}

// DeleteImsSequenceParams deletes ImsSequenceParams by Id and returns error if
// the record to be deleted doesn't exist
func DeleteImsSequenceParams(id string) (err error) {
	o := orm.NewOrm()
	v := ImsSequenceParams{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&ImsSequenceParams{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}


func autoInsertSequenceParams(rtype int,sequenceId string,  user *User) error {
	var m []*ImsSequenceParams
	for i := 0; i < rtype; i++ {
		item := NewImsSeqnunceParams()
		item.Remark = libs.GetImsSequenceParamsNameByType(i)
		item.Type = i
		item.End = time.Now().AddDate(0,i*2,15)
		item.Start = time.Now().AddDate(0,i*2-1,15)
		item.OrgId = user.Organization.Id
		item.DeptId = user.Dept[0].Id
		item.SequenceId = sequenceId
		item.CId = user.Id
		item.Creater = user.Abbr
		item.UId = user.Id
		item.Updater = user.Abbr
		m = append(m ,item)
	}
	o := orm.NewOrm()
	if len(m) == 1 {
		_, err := o.Insert(m[0])
		return err
	} else {
		_, err := o.InsertMulti(len(m), m)
		return err
	}

}




func NewImsSeqnunceParams() *ImsSequenceParams {
	return &ImsSequenceParams{
		Id: libs.UUID(),
		Outlay: 100,
		Count: 5,
		End: time.Now().AddDate(0,2,15),
		Start:time.Now().AddDate(0,0,15),
		Utime:time.Now(),
		Ctime:time.Now(),
		Status: 1,
		Isdelete: 0,
		Seq: 0,
	}
}


func GetImsSeqnunceParamsBySequenceId(id string) ([]ImsSequenceParams, error) {
	o := orm.NewOrm()
	var l []ImsSequenceParams
	_, err := o.QueryTable(new(ImsSequenceParams)).Filter("SequenceId", id).Filter("Isdelete", 0).
		Filter("Status", 1).OrderBy("Type").All(&l)
	return l, err
}